package ru.urfc.portal.ui.client.widgets;

import ru.urfc.portal.ui.client.Style;

import com.extjs.gxt.ui.client.data.ModelData;
import com.extjs.gxt.ui.client.util.Size;
import com.extjs.gxt.ui.client.widget.grid.Grid;
import com.extjs.gxt.ui.client.widget.grid.GridView;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.AnchorElement;
import com.google.gwt.dom.client.Element;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.ui.Widget;

public class MegaGrid extends Grid<ModelData> {

	int maxHeight = -1;
	
	interface Binder extends UiBinder<Widget, MegaGrid> {}
	private static Binder binder = GWT.create(Binder.class);

	@UiField Style style;
	private AnchorElement anchorTemplate = AnchorElement.as(DOM.createAnchor());
	private Element catalogItemTemplate = DOM.createDiv();
	private Element anchorParent = DOM.createDiv();; 
	private Element catalogItemParent = DOM.createDiv();; 
	private Element templatesParent = DOM.createDiv();; 
	{
		templatesParent.appendChild(anchorParent);
		templatesParent.appendChild(catalogItemParent);
		anchorParent.appendChild(anchorTemplate); 
		catalogItemParent.appendChild(catalogItemTemplate);
	}

	public Element getTemplatesParent() {
		return catalogItemParent;
	}
	
	public MegaGrid() {
		super(null, null);
		setView(new GridView() {
			@Override
			protected void resize() {
				MegaGrid.this.checkMaxHeight();
				super.resize();
			}
		});
		binder.createAndBindUi(this);
		setLoadMask(true);
        setAutoHeight(true);
        getView().setForceFit(true);
	}
	
	protected void checkMaxHeight() {
		if (maxHeight > 0) {
			Size size = el().getStyleSize();
			if (size.height < maxHeight) {
				setAutoHeight(true);					
				setHeight(size.height);
			} else {
				setAutoHeight(false);					
				setHeight(maxHeight);
			}
		}
	}

	public Style getStyle() {
		return style;
	}

	public AnchorElement getAnchorTemplate() {
		return anchorTemplate;
	}

	public Element getCatalogItemTemplate() {
		return catalogItemTemplate;
	}

	public int getMaxHeight() {
		return maxHeight;
	}

	/**
	 * Works like autoHeight(true) if calculated height < maxHeight
	 * else works like autoHeight(false) and height = maxHeight
	 * if maxHeight negative - feature disabled 
	 * @param maxHeight
	 */
	public void setMaxHeight(int maxHeight) {
		this.maxHeight = maxHeight;
	}	
	
}